<?php

namespace Frieza\Modules\Push\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmPush\AdmPushTask as mAdmPushTask;
use Doraemon\model\AdmPush\AdmPushTaskGroup as mAdmPushTaskGroup;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\AdmPush\PushTask;
use Doraemon\service\position\UserProfileModule;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\tools\ImgUrl;

class IndexController extends Controller
{

    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");',true);
        Admin::script($this->cancelScript(),true);
    }

    public function index(Request $request, Content $content)
    {
        $requestParams = $request->all();
        $taskCondition = [];
        if (isset($requestParams['id']) && $requestParams['id']) {
            $condition['id'] = mAdmPushTask::selectByWhere(['id' => $requestParams['id'], 'group_id[>]' => 0], 'group_id');
        } else {
            if (isset($requestParams['group_status']) && strlen($requestParams['group_status']) > 0) {
                $condition['group_status'] = $requestParams['group_status'];
            }
            if (isset($requestParams['push_time'])) {
                if (isset($requestParams['push_time']['start']) && strlen($requestParams['push_time']['start']) > 0) {
                    $condition['group_time[>=]'] = strtotime($requestParams['push_time']['start']);
                }
                if (isset($requestParams['push_time']['end']) && strlen($requestParams['push_time']['end']) > 0) {
                    $condition['group_time[<=]'] = strtotime($requestParams['push_time']['end']);
                }
            }
            if (isset($requestParams['task_status']) && strlen($requestParams['task_status']) > 0) {
                $taskCondition['task_status'] = $requestParams['task_status'];
            }
            if (isset($requestParams['push_status']) && strlen($requestParams['push_status']) > 0) {
                $taskCondition['push_status'] = $requestParams['push_status'];
            }
            if (isset($requestParams['task_title']) && strlen($requestParams['task_title']) > 0) {
                $taskCondition['task_title[~]'] = trim($requestParams['task_title']);
            }
        }
        if ($taskCondition) {
            $taskCondition['group_id[>]'] = 0;
            $condition['id'] = mAdmPushTask::selectByWhere($taskCondition, 'group_id');
        }
        $condition['ORDER'] = ['group_time' => 'DESC'];
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];

        $list = PushTask::admGetGroupList($condition);
        $groupList = [];
        if ($list['total'] > 0) {
            foreach ($list['list'] as $groupId => $row) {
                $group = $row['group'];
                $row['expand'] = $this->_getTaskExpand($group);
                $groupList[] = $row;
            }
        }

        $gridModel = new pGridDataModel($groupList, $list['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('id', '任务ID');
                        $filter->between('push_time', '推送时间')->datetime();
                        $filter->equal('push_title', '任务描述');
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('group_status', '排期状态')->select(mAdmPushTaskGroup::GROUP_STATUS);
                        $filter->equal('task_status', '任务状态')->select(mAdmPushTask::TASK_STATUS);
                        $filter->equal('push_status', '推送状态')->select(mAdmPushTask::PUSH_STATUS);
                    });
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增', '', url('/admin/push/create')));
                });

                $grid->column("id", '分组ID')->expand(function () {
                    return $this->expand;
                }, false);
                $grid->column('group_time', '推送时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->group_time);
                });
                $grid->column('group_status_desc', '排期状态')->display(function ($title, Grid\Column $column) {
                    if ($this->group_status == mAdmPushTaskGroup::GROUP_STATUS_NORMAL) {
                        return $column->button('primary btn-sm');
                    } else if ($this->group_status == mAdmPushTaskGroup::GROUP_STATUS_LOCK) {
                        return $column->button('danger btn-sm');
                    } else if ($this->group_status == mAdmPushTaskGroup::GROUP_STATUS_UNLOCK) {
                        return $column->button('warning btn-sm');
                    } else if ($this->group_status == mAdmPushTaskGroup::GROUP_STATUS_SUCCESS) {
                        return $column->button('success btn-sm');
                    } else if ($this->group_status == mAdmPushTaskGroup::GROUP_STATUS_DELETE) {
                        return $column->button('danger btn-sm');
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append('<a href="/admin/push/timer/' . $actions->row->id . '" class="fa fa-clock-o">查看排期</a>');
                    if ($actions->row->is_cancel) {
                        $actions->append('&nbsp;&nbsp;<a class="fa fa-trash cancel-group" data-time="' . date('Y-m-d H:i:s', $actions->row->group_time) . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消排期</a>');
                    }
                    if ($actions->row->is_unlock) {
                        $actions->append('&nbsp;&nbsp;<a class="fa fa-lock unlock-group" data-time="' . date('Y-m-d H:i:s', $actions->row->group_time) . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">解锁排期</a>');
                    }
                    if ($actions->row->is_lock) {
                        $actions->append('&nbsp;&nbsp;<a class="fa fa-unlock lock-group" data-time="' . date('Y-m-d H:i:s', $actions->row->group_time) . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">锁定排期</a>');
                    }

                });
                $grid->footer(function () {
                    $html = '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;注意：排期未锁定，任务状态只有为「已创建任务」的时候，才能排序。如不能排序，可以尝试解锁排期，重置为「已解锁」。</span>';
                    return $html;
                });
            });
        $tab = new Tab();
        $tab->add('定时推送任务列表', $gridList->render());
        $tab->addLink('定时推送任务排期', url('admin/push/timer'));
        $tab->addLink('其他推送任务列表', url('admin/push/other'));
        $content->row($tab);
        return $content
            ->header('定时推送任务列表')
            ->description(' ')
            ->breadcrumb(['text' => '定时推送任务列表']);
    }

    public function other(Request $request, Content $content)
    {
        $requestParams = $request->all();
        if (isset($requestParams['id']) && $requestParams['id']) {
            $condition['OR']['id'] = $requestParams['id'];
            $condition['OR']['group_id'] = $requestParams['id'];
        } else {
            if (isset($requestParams['push_type']) && strlen($requestParams['push_type']) > 0) {
                $condition['push_type'] = $requestParams['push_type'];
            }
            if (isset($requestParams['push_time'])) {
                if (isset($requestParams['push_time']['start']) && strlen($requestParams['push_time']['start']) > 0) {
                    $condition['push_time[>=]'] = $requestParams['push_time']['start'];
                }
                if (isset($requestParams['push_time']['end']) && strlen($requestParams['push_time']['end']) > 0) {
                    $condition['push_time[<=]'] = $requestParams['push_time']['end'];
                }
            }
            if (isset($requestParams['task_status']) && strlen($requestParams['task_status']) > 0) {
                $condition['task_status'] = $requestParams['task_status'];
            }
            if (isset($requestParams['push_status']) && strlen($requestParams['push_status']) > 0) {
                $condition['push_status'] = $requestParams['push_status'];
            }
            if (isset($requestParams['task_title']) && strlen($requestParams['task_title']) > 0) {
                $condition['task_title[~]'] = trim($requestParams['task_title']);
            }
        }
        $condition['ORDER'] = ['push_time' => 'DESC'];
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $condition['push_type'] = mAdmPushTask::PUSH_TYPE_OTHER;
        $list = PushTask::admGetOtherPushList($condition);
        $taskList = $list['list'];
        $gridModel = new pGridDataModel($taskList, $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableColumnSelector();
                $grid->disableExport();
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('id', 'ID');
                        $filter->between('push_time', '推送时间')->datetime();
                        $filter->equal('push_title', '任务描述');
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('task_status', '任务状态')->select(mAdmPushTask::TASK_STATUS);
                        $filter->equal('push_status', '推送状态')->select(mAdmPushTask::PUSH_STATUS);
                    });
                });
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增', '', url('/admin/push/create')));
                });
                $grid->column('id', '任务ID');
                $grid->column('is_recommend', '推送精选')->display(function () {
                    return $this->is_recommend ? '是' : '否';
                });
                $grid->column('task_title', '任务描述');
                $grid->column('push_time', '推送时间');
                $grid->column('task_status_desc', '任务状态')->display(function ($title, Grid\Column $column) {
                    if ($this->task_status == mAdmPushTask::TASK_STATUS_NORMAL) {
                        return $column->label('primary');
                    } else if ($this->task_status == mAdmPushTask::TASK_STATUS_CREATE_DATA) {
                        return $column->label('warning');
                    } else if ($this->task_status == mAdmPushTask::TASK_STATUS_ALREADY_DATA) {
                        return $column->label('success');
                    } else if ($this->task_status == mAdmPushTask::TASK_STATUS_ERR_DATA) {
                        return $column->label('warning');
                    } else if ($this->task_status == mAdmPushTask::TASK_STATUS_DELETE) {
                        return $column->label('danger');
                    }
                });
                $grid->column('push_status_desc', '推送状态')->display(function ($title, Grid\Column $column) {
                    if ($this->push_status == mAdmPushTask::PUSH_STATUS_NORMAL) {
                        return $column->label('primary');
                    } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_IN_PROGRESS) {
                        return $column->label('warning');
                    } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_SUCCESS) {
                        return $column->label('success');
                    } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_DELETE) {
                        return $column->label('danger');
                    }
                });

                $grid->column('user_profile', '分群信息')->userProfile();
                $grid->column('admin_id', '操作人')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                })->width(100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append('<a href="/admin/push/task/' . $actions->row->id . '" class="fa fa-info-circle">查看详情</a>');
                    if ($actions->row->push_status == mAdmPushTask::PUSH_STATUS_NORMAL) {
                        $actions->append('&nbsp;&nbsp;<a class="fa fa-trash cancel-push" data-id="' . $actions->row->id . '" data-time="'. $actions->row->push_time  .'" href="javascript:void(0);">取消推送</a>');
                    }
                });
            });
        $tab = new Tab();
        $tab->addLink('定时推送任务列表', url('admin/push/index'));
        $tab->addLink('定时推送任务排期', url('admin/push/timer'));
        $tab->add('其他推送任务列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('其他推送任务列表')
            ->description(' ')
            ->breadcrumb(['text' => '其他推送任务列表']);
    }

    public function timer(Request $request, Content $content, $groupId = 0)
    {
        $tab = new Tab();
        $tab->addLink('定时推送任务列表', url('admin/push/index'));

        $groupTime = time();
        $startGroupTime = strtotime(date('Y-m-d'));
        $groupList = [];
        if ($groupId) {
            $groupInfo = mAdmPushTaskGroup::getByWhere(['id' => $groupId]);
            if ($groupInfo) {
                $startGroupTime = strtotime(date('Y-m-d', $groupInfo['group_time']));
                $groupTime = $groupInfo['group_time'];
            }
            $groupList[$groupId] = $groupInfo;
        }
        $endGroupTime = $startGroupTime + 86400;
        $condition['push_time[>=]'] = date('Y-m-d H:i:s', $startGroupTime);
        $condition['push_time[<]'] = date('Y-m-d H:i:s', $endGroupTime);
        $condition['push_type'] = [mAdmPushTask::PUSH_TYPE_TIMER, mAdmPushTask::PUSH_TYPE_REPEAT];
        $condition['ORDER'] = ['sort' => 'ASC'];

        $timerTaskList = [];
        $groupTaskList = PushTask::admGetGroupPushList($condition);
        $groupTimeArr = [];
        $inTimeGroup = true;
        foreach ($groupTaskList as $id => $groupInfo) {
            $groupTime = $groupInfo['group_time'];
            $timerTaskList[$groupTime] = $groupInfo;
            $timerTaskList[$groupTime]['group'] = $groupInfo['group'];
            $groupTimeStr = ltrim(date('H:i', $groupTime), "0");
            $groupTimeArr[] = $groupTimeStr;
            if ($inTimeGroup) {
                $inTimeGroup = in_array($groupTimeStr, PushTask::TIME_GROUP) ? true : false;
            }
        }

        $groupTimeArr = $inTimeGroup ? PushTask::TIME_GROUP : $groupTimeArr;

        $groupTitle = date('Y年m月d日', $groupTime) . '任务排期';

        $childTab = new Tab();
        $active = false;

        foreach ($groupTimeArr as $row) {
            $time = strval(date('Y-m-d', $groupTime)) . ' ' . $row;
            $time = strtotime($time);
            if (isset($timerTaskList[$time])) {
                $currActive = false;
                $groupInfo = $timerTaskList[$time];
                if ($groupId && $groupInfo['id'] == $groupId) {
                    $active = true;
                    $currActive = $active;
                } else {
                    if (!$active) {
                        if ($timerTaskList[$time]) {
                            $active = true;
                        }
                        $currActive = $active;
                    }
                }
                $childTab->add($row, $this->getTimerGrid($groupInfo['group'], $groupInfo), $currActive);
            } else {
                $childTab->add($row, $this->getTimerGrid([], []));
            }
        }

        $tab->add('定时推送任务排期', $childTab, true);
        $tab->addLink('其他推送任务列表', url('admin/push/other'));

        $content->row($tab);
        return $content
            ->header($groupTitle)
            ->description(' ')
            ->breadcrumb(['text' => '定时推送任务列表', 'url' => url('admin/push/index')], ['text' => $groupTitle]);
    }

    private function getTimerGrid($list, $groupInfo)
    {
        $gridModel = new pGridDataModel([]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $groupInfo) {
                $grid->disableFilter();
                $grid->paginate($gridModel->getPerPage());
                $grid->disablePagination();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->tools(function (Grid\Tools $tool) use ($groupInfo) {
                    $class = '';
                    $groupStatus = $groupInfo ? $groupInfo['group_status'] : -1;
                    $isCreate = false;
                    if ($groupStatus == mAdmPushTaskGroup::GROUP_STATUS_NORMAL) {
                        $isCreate = true;
                        $class = 'primary';
                    } else if ($groupStatus == mAdmPushTaskGroup::GROUP_STATUS_LOCK) {
                        $class = 'danger';
                    } else if ($groupStatus == mAdmPushTaskGroup::GROUP_STATUS_UNLOCK) {
                        $isCreate = true;
                        $class = 'warning';
                    } else if ($groupStatus == mAdmPushTaskGroup::GROUP_STATUS_SUCCESS) {
                        $class = 'success';
                    } else if ($groupStatus == mAdmPushTaskGroup::GROUP_STATUS_DELETE) {
                        $isCreate = true;
                        $class = 'danger';
                    }
                    if (!$groupInfo || $isCreate) {
                        $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增', '', url('/admin/push/create')));
                    }
                    $tool->append('<div class="btn-group pull-right" style="margin-right: 800px"><span class="btn btn-' . $class . ' btn-sm">' . $groupInfo['group_status_desc'] . '</span></div>');
                    if ($groupInfo['is_cancel']) {
                        $tool->append('<div class="btn-group pull-right" style="margin-right: 10px"><a class="fa fa-trash cancel-group" data-time="' . date('Y-m-d H:i:s', $groupInfo['group_time']) . '" data-id="' . $groupInfo['id'] . '" href="javascript:void(0);">取消排期</a></div>');
                    }
                    if ($groupInfo['is_unlock']) {
                        $tool->append('<div class="btn-group pull-right" style="margin-right: 10px"><a class="fa fa-lock unlock-group" data-time="' . date('Y-m-d H:i:s', $groupInfo['group_time']) . '" data-id="' . $groupInfo['id'] . '" href="javascript:void(0);">解锁排期</a></div>');
                    }
                    if ($groupInfo['is_lock']) {
                        $tool->append('<div class="btn-group pull-right" style="margin-right: 10px"><a class="fa fa-unlock lock-group" data-time="' . date('Y-m-d H:i:s', $groupInfo['group_time']) . '" data-id="' . $groupInfo['id'] . '" href="javascript:void(0);">锁定排期</a></div>');
                    }
                });

                $grid->disableDefineEmptyPage();
                $grid->disablePagination();
                $grid->disableActions();
            });

        $html = '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;提示：任务ID支持拖拽排序,排的越前优先级越高，请尽量将优先级高的排在前面。</span>';
        $html .= '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;例如：未开启用户分群的任务尽量优先级应该排最低。如全量排在最前，则之后的任务不在执行。</span>';
        $html .= '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;注意：排期未锁定，任务状态只有为「已创建任务」的时候，才能排序或增加任务。</span>';
        $html .= '<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;注意：排期锁定，任务状态为「数据准备完成」的时候，如果想给排期增加任务或则重新排序。可以尝试解锁排期，重置为「已解锁」。解锁后需要操作「锁定排期」，当前排期才能被推送。</span>';


        $contentGrid = $this->getTimerContentGrid($list, $groupInfo);

        return $gridList->render() . $contentGrid . $html;
    }

    private function getTimerContentGrid($list, $groupInfo)
    {
        $data = '';
        for ($i = 0; $i <= count(mAdmPushTask::TASK_TYPE); $i++) {
            if (!isset($list[$i])) {
                continue;
            }
            $gridModel = new pGridDataModel($list[$i]);
            $gridList = Admin::grid($gridModel,
                function (Grid $grid) use ($gridModel, $groupInfo, $i) {
                    $grid->setTitle('优先级' . mAdmPushTask::PUSH_LEVEL_DESC[$i]);
                    $grid->disableFilter();
                    $grid->paginate($gridModel->getPerPage());
                    $grid->disablePagination();
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->disableCreateButton();
                    if ($groupInfo['is_sort']) {
                        $grid->column('id', '任务ID（拖拽排序）')->sort();
                    } else {
                        $grid->column('id', '任务ID（拖拽排序）');
                    }
                    $grid->column('push_type', '推送类型')->display(function () {
                        return mAdmPushTask::TASK_TYPE[$this->push_type];
                    });
                    $grid->column('push_level', '优先级')->display(function () {
                        return mAdmPushTask::PUSH_LEVEL_DESC[$this->push_level];
                    });
                    $grid->column('is_recommend', '推送精选')->display(function () {
                        return $this->is_recommend ? '是' : '否';
                    });
                    $grid->column('task_title', '任务描述');
                    $grid->column('push_time', '推送时间');
                    $grid->column('task_status_desc', '任务状态')->display(function ($title, Grid\Column $column) {
                        if ($this->task_status == mAdmPushTask::TASK_STATUS_NORMAL) {
                            return $column->label('primary');
                        } else if ($this->task_status == mAdmPushTask::TASK_STATUS_CREATE_DATA) {
                            return $column->label('warning');
                        } else if ($this->task_status == mAdmPushTask::TASK_STATUS_ALREADY_DATA) {
                            return $column->label('success');
                        } else if ($this->task_status == mAdmPushTask::TASK_STATUS_ERR_DATA) {
                            return $column->label('warning');
                        } else if ($this->task_status == mAdmPushTask::TASK_STATUS_DELETE) {
                            return $column->label('danger');
                        }
                    });
                    $grid->column('push_status_desc', '推送状态')->display(function ($title, Grid\Column $column) {
                        if ($this->push_status == mAdmPushTask::PUSH_STATUS_NORMAL) {
                            return $column->label('primary');
                        } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_IN_PROGRESS) {
                            return $column->label('warning');
                        } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_SUCCESS) {
                            return $column->label('success');
                        } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_DELETE) {
                            return $column->label('danger');
                        }
                    });
                    $grid->column('user_profile', '分群信息')->userProfile();
                    $grid->column('admin_id', '操作人')->display(function () {
                        return Admin::user()->find($this->admin_id)->name;
                    });
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableEdit();
                        $actions->disableDelete();
                        $actions->append('<a href="/admin/push/task/' . $actions->row->id . '" class="fa fa-info-circle">查看详情</a>');
                        if ($actions->row->is_cancel) {
                            $actions->append('&nbsp;&nbsp;<a class="fa fa-trash cancel-push" data-id="' . $actions->row->id . '" data-time="'. $actions->row->push_time  .'" href="javascript:void(0);">取消推送</a>');
                        }
                    });

                    $grid->disablePagination();
                });

            $data = $data . $gridList->render();
        }

        return $data ?? '';
    }

    public function create(Request $request, Content $content, $id = 0)
    {
        $header = $id ? '查看推送任务' : '添加推送任务';
        $description = $id ? '仅提供查看，不支持编辑' : '推送时间至少要大于当前时间半个小时「>30分钟」';

        $info = PushTask::admGetPushTaskInfo($id);
        if ($info && $info['content_select'] == 0) {
            $info['basic_content'] = $info['ios_content'];
        }
        $tab = new Tab();
        if ($id && !$info) {
            $tab->add('基础信息', '<h4>不存在的任务</h4>');
            return $content->header($header)->description(' ')->breadcrumb(
                ['text' => '定时推送任务列表', 'url' => url('admin/push/index')],
                ['text' => $header])
                ->row($tab);
        }
        $form = new Form($info);
        $tab->add('基础信息', $form);
        $form->hidden('id');
        if (!$info) {
            $form->fieldChange('push_type', '推送类型', $form)
                ->options(mAdmPushTask::TASK_TYPE)
                ->default(mAdmPushTask::PUSH_TYPE_TIMER)
                ->callablePreCommon(function (Form $form) use ($info) {
                })->callableMap([
                    1 => function (Form $form) use ($info) {
                        $form->date('push_day', '推送日期');
                        $form->radio('push_hour', '推送时间')->options(PushTask::TIME_GROUP)
                            ->default(PushTask::TIME_GROUP_ONE)
                            ->help('推送时间至少要大于当前时间半个小时「>30分钟」。23:30截止推送，未推送的消息会丢弃。');
                    },
                    2 => function (Form $form) {
                        $form->datetime('push_time', '推送时间')
                            ->default(date('Y-m-d H:i:s', strtotime('+2 minutes')))
                            ->help('推送时间至少要大于当前时间半个小时「>30分钟」。指定用户，推送时间不能小于当前时间1分钟。23:30截止推送，未推送的消息会丢弃。');
                    },
                    3 => function (Form $form) {
                        $form->radio('push_level', '推送优先级')->options(mAdmPushTask::PUSH_LEVEL_DESC)
                            ->default(mAdmPushTask::PUSH_LEVEL_HIGH)
                            ->help('比定时任务优先级高的建议选择「高」，反之则选择「低」。23:30截止推送，未推送的消息会丢弃。');
                        $form->radio('push_hour', '推送时间')->options(PushTask::TIME_GROUP)
                            ->default(PushTask::TIME_GROUP_ONE)
                            ->help('推送时间至少要大于当前时间半个小时「>30分钟」。23:30截止推送，未推送的消息会丢弃。');
                    }
                ]);
        } else {
            $form->radio('push_type', '推送类型')
                ->options(mAdmPushTask::TASK_TYPE)
                ->default($info['push_type'])
                ->disable();
            if (isset($info['group_id']) && $info['group_id']) {
                $form->text('group_id', '分组ID')->width("110px")->readonly();
            }
            if ($info['push_type'] == mAdmPushTask::PUSH_TYPE_TIMER) {
                $form->date('push_day', '推送日期')
                    ->readonly();
                $form->radio('push_hour', '推送时间')->options(PushTask::TIME_GROUP)
                    ->default(PushTask::TIME_GROUP_ONE)
                    ->disable();
            } else if ($info['push_type'] == mAdmPushTask::PUSH_TYPE_OTHER) {
                $form->datetime('push_time', '推送时间')
                    ->readonly();
            } else if ($info['push_type'] == mAdmPushTask::PUSH_TYPE_REPEAT) {
                $form->radio('push_level', '推送优先级')->options(mAdmPushTask::PUSH_LEVEL_DESC)
                    ->default(mAdmPushTask::PUSH_LEVEL_HIGH)
                    ->help('比定时任务优先级高的建议选择「高」，反之则选择「低」')
                    ->disable();
                $form->radio('push_hour', '推送时间')->options(PushTask::TIME_GROUP)
                    ->default(PushTask::TIME_GROUP_ONE)
                    ->disable();
            }
        }
        $form->text('task_title', '任务描述')->help('任务描述必填')->required();
        /*
        $form->select('check_repeat', '重复推送')
            ->options([0 => '不检查重复', '检查重复'])
            ->help('检查重复，接受过推送的用户2小时内不再接受任何推送')->default(0);
         */
        $form->text('push_title', '推送标题')->help('非必填');
        $form->fieldChange('content_select', '推送内容', $form)
            ->options([0 => '推送内容公用', 1 => '推送内容分开'])
            ->default(0)
            ->required()
            ->callablePreCommon(function (Form $form) use ($info) {
            })->callableMap([
                0 => function (Form $form) use ($info) {
                    $form->textarea('basic_content', '公用')->help('推送内容必填');
                },
                1 => function (Form $form) {
                    $form->textarea('ios_content', 'IOS')->help('推送内容必填');
                    $form->textarea('android_content', 'Android')->help('推送内容必填');
                },
            ]);
        $form->imgUpload('push_image', '图片', false, [
            'imgType' => ImgUrl::APPTYPE_APP,
            'imgSize' => ImgUrl::IMAGE_SIZE_APP_PUSH ])
            ->help("推送图片，非必填");
        $form->fieldChange('is_recommend', '推送精选', $form)
            ->options([0 => '否', 1 => '是'])
            ->default(0)
            ->required()
            ->callablePreCommon(function (Form $form) use ($info) {
            })->callableMap([
                0 => function (Form $form) {
                },
                1 => function (Form $form) {
                    $form->text('recommend_pic', '图片地址');
                },
            ]);
        $form->divider();
        $form->linkSelect('link', '跳转链接');
        $form->html('<span class="help-block"><i class="fa fa-info-circle"></i>&nbsp;推送的链接必须选择</span>');
        $form->divider();
        $form->userProfile('user_profile', '用户分群')
            ->options(\Doraemon\service\position\UserProfileModule::$other_position_rules)
            ->generate();
        $form->disableReset();
        if ($id) {
            $form->disableSubmit();
        } else {
            $form->action(url('admin/push/save'));
        }

        return $content->header($header)->description($description)->breadcrumb(
            ['text' => '定时推送任务列表', 'url' => url('admin/push/index')],
            ['text' => $header])
            ->row($tab);
    }

    public function save(Request $request, Content $content)
    {
        try {
            $linkParams = $request->input("link_params", "");
            $pushHour = $request->input('push_hour', "");
            $pushHour = intval($pushHour);
            $pushHour = strlen($pushHour) > 0 ? PushTask::TIME_GROUP[$pushHour] : '';
            $contentSelect = $request->input('content_select', 0);
            $basicContent = $request->input('basic_content', '');
            $iosContent = $request->input('ios_content', '');
            $androidContent = $request->input('android_content', '');
            if ($contentSelect == 0) {
                $iosContent = $basicContent;
                $androidContent = $basicContent;
            }
            $push_image = $request->input('push_image', '');
            $baseData = [
                'id' => $request->input('id', 0),
                'group_id' => $request->input('group_id', 0),
                'push_type' => $request->input('push_type', 0),
                'push_level' => $request->input('push_level', 1),
                'push_day' => $request->input('push_day', ''),
                'push_hour' => $pushHour,
                'push_time' => $request->input('push_time', ''),
                'task_title' => $request->input('task_title', ''),
                'check_repeat' => $request->input('check_repeat', 0),
                'push_title' => $request->input('push_title', ''),
                'ios_content' => $iosContent,
                'android_content' => $androidContent,
                'link_type' => $request->input('link_type', ''),
                'link_params' => $linkParams ? json_encode($linkParams, JSON_UNESCAPED_UNICODE) : '',
                'is_recommend' => $request->input('is_recommend', 0),
                'recommend_pic' => $request->input('recommend_pic', ''),
                'admin_id' => Admin::user()->id,
                'push_image' => $push_image,
            ];

            //分群信息
            $userProfile = $request->input('user_profile', []);
            if ($baseData['push_type'] == mAdmPushTask::PUSH_TYPE_TIMER) {
                if ($baseData['id'] && !$baseData['group_id']) {
                    throw new \Exception('任务数据错误');
                }
                if (!$baseData['push_day'] || !$baseData['push_hour']) {
                    throw new \Exception('请选择推送日期和推送时间');
                }
                $baseData['push_time'] = date('Y-m-d H:i:s', strtotime($baseData['push_day'] . ' ' . $baseData['push_hour']));
            } else if ($baseData['push_type'] == mAdmPushTask::PUSH_TYPE_OTHER) {
                if (!$baseData['push_time']) {
                    throw new \Exception('请选择推送时间');
                }
            } else if ($baseData['push_type'] == mAdmPushTask::PUSH_TYPE_REPEAT) {
                if (!$baseData['push_hour']) {
                    throw new InputErrorException('请选择推送时间', InputErrorException::DEFAULT_CODE, 'push_hour');
                }
                $baseData['push_time'] = date('Y-m-d H:i:s', strtotime($baseData['push_hour']));
            }
            $rs = UserProfileModule::rules($userProfile);
            // 其他任务,指定用户，不受30分钟限制
            if ($baseData['push_type'] == mAdmPushTask::PUSH_TYPE_OTHER && $rs && isset($rs['rules'][PositionRules::RULE_TYPE_UID]) && $rs['rules'][PositionRules::RULE_TYPE_UID]) {
                if (strtotime($baseData['push_time']) <= strtotime("-2 minutes")) {
                    throw new \Exception('指定uid的其他推送，推送时间不能小于前时间2分钟。你设置的时间：' . $baseData['push_time']);
                }
            } else {
                if (strtotime($baseData['push_time']) <= strtotime("+30 minutes")) {
                    throw new \Exception('推送时间必须大于当前时间30分钟。你设置的时间：' . $baseData['push_time']);
                }
            }
            if (!$baseData['ios_content'] || !$baseData['android_content']) {
                throw new \Exception('推送内容必须填写');
            }
            if (!$baseData['link_type']) {
                throw new \Exception('推送的跳转链接必须填写');
            }
            //添加任务
            $result = PushTask::addTask($baseData, $userProfile);
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            if ($result) {
                return redirect(url('/admin/push/index'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            \Doraemon\tools\Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        foreach ($sortInfo as $id => $sort) {
            PushTask::admSortTask($sort, $id);
        }
    }

    public function cancel(Request $request, $id = 0)
    {
        try {
            if (!$id) {
                throw new \Exception('不存在的id');
            }
            PushTask::admCancelTask($id, Admin::user()->id);
            $success = [
                'title' => '任务 ID: ' . $id . ' 取消成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '取消任务失败',
                'code' => 0,
                'status' => false,
                'msg' => '错误信息#file:' . $e->getFile() . '#line:' . $e->getLine() . '#msg:' . $e->getMessage(),
            ];
        }
        return response()->json($success);
    }

    public function cancelGroup(Request $request, $id = 0)
    {
        try {
            if (!$id) {
                throw new \Exception('不存在的id');
            }
            PushTask::admCancelTaskGroup($id, Admin::user()->id);
            $success = [
                'title' => '分组 ID: ' . $id . ' 取消排期成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '取消排期失败',
                'code' => 0,
                'status' => false,
                'msg' => '错误信息#file:' . $e->getFile() . '#line:' . $e->getLine() . '#msg:' . $e->getMessage(),
            ];
        }
        return response()->json($success);
    }

    public function unlockGroup(Request $request, $id = 0)
    {
        try {
            if (!$id) {
                throw new \Exception('不存在的id');
            }
            PushTask::admUnLockTaskGroup($id, Admin::user()->id);
            $success = [
                'title' => '分组 ID: ' . $id . ' 解除锁定排期成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '解锁排期失败',
                'code' => 0,
                'status' => false,
                'msg' => '错误信息#file:' . $e->getFile() . '#line:' . $e->getLine() . '#msg:' . $e->getMessage(),
            ];
        }
        return response()->json($success);
    }

    public function lockGroup(Request $request, $id = 0)
    {
        try {
            if (!$id) {
                throw new \Exception('不存在的id');
            }
            PushTask::admLockTaskGroup($id, Admin::user()->id);
            $success = [
                'title' => '分组 ID: ' . $id . ' 锁定排期成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '锁定排期失败',
                'code' => 0,
                'status' => false,
                'msg' => '错误信息#file:' . $e->getFile() . '#line:' . $e->getLine() . '#msg:' . $e->getMessage(),
            ];
        }
        return response()->json($success);
    }

    private function _getTaskExpand($groupArr)
    {
        $row = new Row();
        if ($groupArr) {
            $GirdModel = new pGridDataModel($groupArr, null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableExport();
            $grid->column('id', '任务ID');
            $grid->column('push_type', '推送类型')->display(function () {
                return mAdmPushTask::TASK_TYPE[$this->push_type];
            });
            $grid->column('push_level', '优先级')->display(function () {
                return mAdmPushTask::PUSH_LEVEL_DESC[$this->push_level];
            });
            $grid->column('is_recommend', '推送精选')->display(function () {
                return $this->is_recommend ? '是' : '否';
            });
            $grid->column('task_title', '任务描述');
            $grid->column('push_time', '推送时间');
            $grid->column('task_status_desc', '任务状态')->display(function ($title, Grid\Column $column) {
                if ($this->task_status == mAdmPushTask::TASK_STATUS_NORMAL) {
                    return $column->label('primary');
                } else if ($this->task_status == mAdmPushTask::TASK_STATUS_CREATE_DATA) {
                    return $column->label('warning');
                } else if ($this->task_status == mAdmPushTask::TASK_STATUS_ALREADY_DATA) {
                    return $column->label('success');
                } else if ($this->task_status == mAdmPushTask::TASK_STATUS_ERR_DATA) {
                    return $column->label('warning');
                } else if ($this->task_status == mAdmPushTask::TASK_STATUS_DELETE) {
                    return $column->label('danger');
                }
            });
            $grid->column('push_status_desc', '推送状态')->display(function ($title, Grid\Column $column) {
                if ($this->push_status == mAdmPushTask::PUSH_STATUS_NORMAL) {
                    return $column->label('primary');
                } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_IN_PROGRESS) {
                    return $column->label('warning');
                } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_SUCCESS) {
                    return $column->label('success');
                } else if ($this->push_status == mAdmPushTask::PUSH_STATUS_DELETE) {
                    return $column->label('danger');
                }
            });

            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('admin_id', '操作人')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            })->width(100);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append('<a href="/admin/push/task/' . $actions->row->id . '" class="fa fa-info-circle">查看详情</a>');
                if ($actions->row->is_cancel) {
                    $actions->append('&nbsp;&nbsp;<a class="fa fa-trash cancel-push" data-id="' . $actions->row->id . '" data-time="'. $actions->row->push_time  .'" href="javascript:void(0);">取消推送</a>');
                }
            });
            $grid->disablePagination();
            $row->column('12', $grid);
            return $row->render();
        }
        return '';

    }

    private function cancelScript()
    {
        return <<<SCRIPT
        $('.cancel-push').unbind('click').click(function(){
            var id= $(this).data('id');
            var time = $(this).data('time');
            layer.confirm('任务'+id+'，推送时间'+time+'，确定要取消吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/cancel';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        function closeLayer() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        }
        $('.cancel-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要取消「'+group_time+'」的排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/cancelGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.unlock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要解除锁定的「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/unlockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        })
        $('.lock-group').unbind('click').click(function(){
            var id= $(this).data('id');
            var group_time=$(this).data('time');
            layer.confirm('确定要锁定「'+group_time+'」排期吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/push/task/' +  id  + '/lockGroup';
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            });
        });
SCRIPT;
    }


}
